package com.boxin.ims.modules.wechat.busi;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.ad.entity.Advertisement;
import com.boxin.ims.modules.momarketing.entity.CustomPage;
import com.boxin.ims.modules.momarketing.service.CustomPageService;
import com.boxin.ims.modules.wechat.entity.BusinessNewsReply;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.SignupConfig;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.BusinessNewsReplyService;
import com.boxin.ims.modules.wechat.service.SignupConfigService;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.utils.DataUtils;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;


/**
 * @author Jakemanse
 * @date 2013-9-23
 * @function <p>签到处理器 </p>
 */
@Service
public class SignProcessor extends BusinessProcessor {
	
	@Autowired
	UserDefineService userDefineService;
	
	@Autowired
	BusinessNewsReplyService businessNewsReplyService;
	
	@Autowired
	SignupConfigService signupConfigService;
	
	@Autowired
	WechatDaoHelper wechatDaoHelper;
	
	
	@Autowired
	private CustomPageService customPageService;

	
	public SignProcessor() {
		super();
	}
	
	
	@Override
	public ProcessMessage process() {
		WechatMember member =	memberCheckAndReply();
		if(member != null){
			String reply  = "";
			String upcon = textMessage.getContent();
			System.out.println("-------user.getId() : "+ user.getId()+"----------");
			UserBusiness userBusiness = WechatUtils.getUserBusinessByKeyWords(user.getId(),upcon);
			
			UserDefine userDefine = WechatUtils.getUserDefineByUserId(weChat.getUser().getId());	//定义
			if(userDefine != null && UserDefine.NO.equals(userDefine.getSignSwitch())){	//签到服务停止
				reply =  "签到积分活动已停止,启动时间请等通知,谢谢!";
				if(StringUtils.isNotEmpty(userDefine.getSignSwitchDesc())){
					reply = userDefine.getSignSwitchDesc();
				}
				
				writeToUser(reply);
				return null;
			}
			
			
			String signOrder = wechatDaoHelper.queryMemberSignupOrder(user.getId());
			
			SignupConfig signupConfig=  signupConfigService.getByUserId(member.getUser().getId());
			
			boolean signuped = DateUtils.getTodayString().equals(member.getLastSignTime());
			
			String msgType = userBusiness.getMsgType();			//回复类型
			
			//当签到过后显示给用户今日签到的分数
			Integer todayScore =0;
			
			
			
			if(signuped){	//今天已签到过了
				if(signupConfig!=null && signupConfig.getStartup()){
					todayScore = signupConfigService.getTodayScore(userDefine, member,signupConfig);//计算今天签到应该得到多少分
				}else{
					todayScore=userDefine.getSignScore();
				}
				
				double score = ((double)member.getScore())/1000;
				//score = (score==null) ? 0 :score;
				reply = WechatUtils.processUserBusinessReply(user.getId(), upcon, score);
				
				if(UserBusiness.MSG_TYPE_NEWS.equals(msgType)){
					//图文回复处理
					replyNewsMessage(member, userBusiness, todayScore,signOrder, signuped);	
					return null;
				}else{
					
					if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(reply)){
						reply = "今天您已签到过了,您当前的积分为:"+score+"分!";
					}else{
						reply = reply.replaceAll("%分值%",((double)todayScore)/1000 + "");
						reply = reply.replaceAll("%排名%",signOrder + "");
						reply = reply.replaceAll("%积分%", score+ "");
						reply = reply.replaceAll("%连续签到%", member.getSignupCount()+"");
						reply =  "今天您已签到过了," + reply;
					}
				}
				
				//回复内容：
				writeToUser(reply);
				
				return null;
				
				
			}else{//今天未签到
				if(signupConfig!=null && signupConfig.getStartup()){
					if(signupConfig.getCycle()!=null){
						if(signupConfig.getCycle()!=0){
							if(member.getSignupCount()>=signupConfig.getCycle()){
								member.setSignupCount(0);
							}
						}
					}
				}
				signupConfigService.isSignup(signupConfig,member);//记录连续签到的天数
				
				if(signupConfig!=null && signupConfig.getStartup()){
					todayScore = signupConfigService.getTodayScore(userDefine, member,signupConfig);//计算今天签到应该得到多少分
				}else{
					todayScore=userDefine.getSignScore();
				}
				
				if(UserBusiness.MSG_TYPE_NEWS.equals(msgType)){
					Integer score=0;
					if(signupConfig!=null && signupConfig.getStartup()){
						
						// 签到成功
						score=member.getActiveScore();
						member.setUpdateTime(new Date());
						member.setLastSignTime(DateUtils.getTodayString());
						
						score+=todayScore;	//今天就得积分,今日签到积分转换成厘为单位
						member.setActiveScore(score);
						member.setScore(member.getScore()+userDefine.getSignScore());
						wechatMemberService.save(member);
						
						//记录签到
						ScoreUtils.addWechatMemberSignScore(member,todayScore);
					}else{
						
						score = member.getActiveScore();
						score = (score==null) ? 0 :score+userDefine.getSignScore();
						member.setActiveScore(score);
						member.setScore(member.getScore()+userDefine.getSignScore());
						member.setUpdateTime(new Date());
						member.setLastSignTime(DateUtils.getTodayString());
						wechatMemberService.save(member);
						
						
						ScoreUtils.addWechatMemberSignScore(member,userDefine.getSignScore());
						
					}
					
					
					//图文回复处理
					System.out.println("userBusiness.getId():  "+userBusiness.getId()+"=============");
					System.out.println("todayScore:  "+todayScore+"=============");
					System.out.println("signuped:  "+signuped+"=============");
					replyNewsMessage(member, userBusiness, todayScore,signOrder, signuped);	
					return null;
				}else{
					
					Integer score=0;
					if(signupConfig!=null && signupConfig.getStartup()){
						signupConfigService.isSignup(signupConfig,member);//记录连续签到的天数
						// 签到成功
						score=member.getActiveScore();//改
						member.setUpdateTime(new Date());
						member.setLastSignTime(DateUtils.getTodayString());
						
						score+=todayScore;	//今天就得积分
						member.setActiveScore(score);
						member.setScore(member.getScore()+userDefine.getSignScore());
						wechatMemberService.save(member);
						
						reply = WechatUtils.processUserBusinessReply(user.getId(),	upcon, score);
						if (com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(reply)) {
							reply = "签到成功,您当前的积分为:" + ((double)score)/1000 + "分!";
						} else {
							reply = reply.replaceAll("%分值%",((double)todayScore)/1000 + "");
							reply = reply.replaceAll("%排名%",signOrder + "");
							reply = reply.replaceAll("%积分%", ((double)score)/1000 + "");
							reply = reply.replaceAll("%连续签到%", member.getSignupCount()+"");
						}
						//记录签到
						ScoreUtils.addWechatMemberSignScore(member,todayScore);
					}else{
						
						score = member.getActiveScore();
						score = (score==null) ? 1 :score+userDefine.getSignScore();
						member.setActiveScore(score);
						member.setScore(userDefine.getSignScore()+member.getScore());
						member.setUpdateTime(new Date());
						member.setLastSignTime(DateUtils.getTodayString());
						wechatMemberService.save(member);
						
						reply = WechatUtils.processUserBusinessReply(user.getId(), upcon, score);
						if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(reply)){
							reply = "签到成功,您当前的积分为:"+((double)score)/1000+"分!";
						}else{
							reply = reply.replaceAll("%分值%", ((double)userDefine.getSignScore())/1000+"");
							reply = reply.replaceAll("%积分%", ((double)score)/1000+"");
							reply = reply.replaceAll("%连续签到%", member.getSignupCount()+"");
						}
						
						ScoreUtils.addWechatMemberSignScore(member,userDefine.getSignScore());
					}
					
				}
				
			}
			
			
			//回复内容：
			writeToUser(reply);
			
		}
			
		return null;
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-31  上午11:32:56
	 * @function <p> 多图文回复 </p>
	 * @param member
	 * @param userBusiness
	 * @param todayScore
	 * @param finalScore
	 * @param signuped
	 */
	private void replyNewsMessage(WechatMember member,UserBusiness userBusiness,int todayScore,String signOrder,boolean signuped ){
		double finalScore = ((double)member.getScore())/1000;
		List<BusinessNewsReply>	bnrList = businessNewsReplyService.findByTypeSourceId("business", user.getId() , userBusiness.getId()+"");
		if(bnrList != null  && !bnrList.isEmpty() ){
			
			List<NewsReply> newsReplies = DataUtils.convertToNewsReplyList(bnrList);
			if(newsReplies!=null  && !newsReplies.isEmpty()){
				for(NewsReply newsReply : newsReplies){
					String title = newsReply.getTitle();
					if(StringUtils.isNotEmpty(title)){
						title = title.replaceAll("%分值%", ((double)todayScore)/1000+"");
						title = title.replaceAll("%积分%", finalScore+"");
						title = title.replaceAll("%连续签到%", member.getSignupCount()+"");
						title = title.replaceAll("%排名%",signOrder + "");
						if(0==member.getSignupCount()){
							member.setSignupCount(1);
						}
						title = title.replaceAll("%连续签到%", member.getSignupCount()+"");
						newsReply.setTitle(title);
					}
					
					String desc = newsReply.getDescription();
					desc = desc.replaceAll("%分值%", ((double)todayScore)/1000+"");
					desc = desc.replaceAll("%积分%", finalScore+"");
					desc = desc.replaceAll("%连续签到%", member.getSignupCount()+"");
					desc = desc.replaceAll("%排名%",signOrder + "");
					newsReply.setDescription(desc);
				}
				
				
				//更新URL 将系统中动态的参数值补充到URL中
				replaceUrlParameters(newsReplies);
				
				
				//
				if(signuped){
					NewsReply newsReply = newsReplies.get(0);
					//改
					System.out.println((double)member.getScore()+"------------------------");
					newsReply.setDescription( "您今天已经签到过了,请明天再来试试吧,今天是连续签到的第"+member.getSignupCount()+"天,您当前的积分是"+((double)member.getScore())/1000+"分."  );
					if(newsReplies.size()>1){
						NewsReply newsReply2 = newsReplies.get(1);
						System.out.println((double)member.getScore()+"======================");
						newsReply2.setTitle( "您今天已经签到过了,请明天再来试试吧,今天是连续签到的第"+member.getSignupCount()+"天,您当前的积分是"+((double)member.getScore())/1000+"分."  );
						
					}
				}else{
					//只有成功签到后 可以获得该广告奖品
					//广告处理
					List<NewsReply>  adnews = advertisementServicesNewsList();
					
					System.out.println("adnews.size()---"+adnews.size());
					for(int i = 0 ; i<adnews.size(); i++){
						System.out.println("adnews++++---"+adnews);
					}
					if(adnews!=null && !adnews.isEmpty()){
						newsReplies.addAll(adnews);
					}
				}
				
				List<NewsReply>  newsReplyList =  WechatUtils.getWitticism(null, null, null,null);
				
				for (int i = 0; i < newsReplyList.size(); i++) {
					newsReplies.add(newsReplyList.get(i));
				}

				
				//广告积分
				//广告积分
				NewsReply  advertScorenews = addAdvertNews();
				System.out.println("advertScorenews = "+ advertScorenews +"     32484383427234");
				if(advertScorenews != null){
					newsReplies.add(advertScorenews);
				}
				System.out.println("newsReplies.size()---"+newsReplies.size());
				this.writeMultiImagesToUser(newsReplies);
			}
		}
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-16  下午3:40:27
	 * @function <p> 添加广告积分 </p>
	 * @return
	 */
	public NewsReply addAdvertNews(){

		List<CustomPage>  pageList = 	null;//customPageService.findAllByUserId(user.getId());
		pageList = 	customPageService.findAdvertPagesByUserId(user.getId());
		if(pageList != null && !pageList.isEmpty()){
			Random rand = new Random();
			int  n  = 0;
			int limit = 0;
			while(true){
				
				try {
					n  = rand.nextInt(pageList.size());
				} catch (Exception e) {
					n=0;
					break;
				}
				if(n>=0 && n <= pageList.size()-1){
					break;
				}
				
				
				if(limit>=15){	//
					n=0;
					break;
				}
				limit ++;
			}
			
			CustomPage page = pageList.get(n);
			
//			linktoProcessor.setUser(user);
//			linktoProcessor.setWeChat(weChat);
//			linktoProcessor.setOpenId(openId);
//			linktoProcessor.setRequest(request);
//			linktoProcessor.setResponse(response);
//			linktoProcessor.setMessageMap(map);
//			linktoProcessor.setTextMessage(processorMessage);
			
			String picUrl = "http://weixin.zhaotang.net/zt/userfiles/pages/"+page.getPicname();
			String siteUrl = "http://weixin.zhaotang.net/zt/f/site/toRichpage/"+page.getId()+"?uid="+user.getId()+"&wechatId="+openId;
			
//			linktoProcessor.writeImageToUser(page.getName(), "", url, siteUrl);
			
			NewsReply  newsReply = new NewsReply();
			newsReply.setArticleCount(0);
			newsReply.setPicUrl(picUrl);
			newsReply.setUrl(siteUrl);
			newsReply.setTitle(page.getName());
			
			
			return newsReply;
		}
		
		return null;
	
	}


	@Override
	public boolean isNeedBeMember() {
		return true;
	}

}
